import * as xlsx from "xlsx";
import { toExportData, toSystemData } from "./convert";
import { formatDate } from "@/utils/hust/formatTime.js";
import XLSXS from "xlsx-js-style";

/**
 * 读取文件数据
 * @param file
 * @returns
 */
const readFile = (file, txt) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    if (txt) reader.readAsText(file, "utf8");
    else reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target?.result);
    };
  });
};

//导出excel文件-并修改表头样式
export function exportExcelData(data, title, department, eventInfo) {
  var filename = `${title}.xlsx`;
  var sheetname = eventInfo.typeText;

  const headMapper = {
    date: "日期",
    time: "时间",
    zu_t: "控制上游水位(m)",
    zd_t: "预计下游水位(m)",
    h_t: "预计水头(m)",
    q_in_t: "预计上游来水(m³/s)",
    q_out_t: "枢纽总下泄(m³/s)",
    q_unit_t: "电站下泄(m³/s)",
    q_gate_t: "泄水闸下泄(m³/s)",
    gate_plan: "泄水闸调度方案",
    unit_plan: "电站调度方案",
    navi_plan: "船闸调度方案",
  };
  var colCount = Object.keys(headMapper).length;
  var rowCount = data.length + 4;
  var xlsData = [];
  var head = new Array(colCount);
  head[0] = title;
  xlsData.push(head);
  head = new Array(colCount);
  head[0] = `制表时间：${formatDate(new Date(), "YYYY年m月d日 H时")}`;
  head[9] = `制表单位：${department}`;
  xlsData.push(head);
  xlsData.push(Object.keys(headMapper).map((key) => headMapper[key]));
  data.forEach((x) => {
    xlsData.push(
      Object.keys(headMapper).map((key) =>
        key == "date" ? formatDate(new Date(x[key]), "m月d日") : x[key]
      )
    );
  });
  head = new Array(colCount);
  head[0] =
    `备注：本表中所有数据，是根据《${eventInfo.filename}》要求、` +
    "近期汉江流域水情及以往调度经验，通过分析计算得出，" +
    "可能存在一定误差，需在调度过程中逐步修正。";
  xlsData.push(head);

  const sheet = XLSXS.utils.aoa_to_sheet(xlsData);
  Object.keys(sheet).forEach((key) => {
    if (key[0] != "!") {
      sheet[key].s = {
        font: { name: "仿宋", sz: 12, bold: false },
        alignment: {
          vertical: "center",
          horizontal: "center",
          wrapText: true,
        },
        border: {
          top: { style: "thin" },
          bottom: { style: "thin" },
          left: { style: "thin" },
          right: { style: "thin" },
        },
      };
    }
  });
  //设置字体
  sheet["A1"].s.font = { name: "黑体", sz: 24, bold: false };
  sheet["A2"].s.alignment.horizontal = "left";
  sheet["J2"].s.alignment.horizontal = "right";
  var footer = xlsx.utils.encode_cell({ r: rowCount - 1, c: 0 });
  sheet[footer].s.alignment.horizontal = "left";

  //设置边框
  delete sheet["A1"].s.border;
  delete sheet["A2"].s.border;
  delete sheet["J2"].s.border;
  delete sheet[footer].s.border;

  // 设置所有行高列宽
  sheet["!rows"] = new Array(xlsData.length).fill({ hpx: 28.25 });
  sheet["!rows"][0] = { hpx: 31.5 };
  sheet["!rows"][2] = { hpx: 51 };
  sheet["!cols"] = new Array(colCount).fill({ wpx: 70 });
  sheet["!cols"][colCount - 3] = { wpx: 220 };

  //设置合并
  sheet["!merges"] = [
    {
      s: { r: 0, c: 0 },
      e: { r: 0, c: colCount - 1 },
    },
    {
      s: { r: 1, c: 0 },
      e: { r: 1, c: 3 },
    },
    {
      s: { r: 1, c: 9 },
      e: { r: 1, c: colCount - 1 },
    },
    {
      s: { r: rowCount - 1, c: 0 },
      e: { r: rowCount - 1, c: colCount - 1 },
    },
  ];
  var spanColIdx = [0, colCount - 3, colCount - 2, colCount - 1];
  spanColIdx.forEach((idx) => {
    var s = { r: 3, c: idx };
    for (var i = 1; i < data.length; i++) {
      var e = { r: 3 + i, c: idx };
      var cell = xlsx.utils.encode_cell(e);      
      if (sheet[cell].v != sheet[xlsx.utils.encode_cell(s)].v) {
        if (e.r - s.r > 1) {
          sheet["!merges"].push({ s, e: { r: e.r - 1, c: e.c } });
          s = e;
        }
      } else {
        if (i == data.length - 1 && e.r - s.r > 0) {
          sheet["!merges"].push({ s, e: { r: e.r, c: e.c } });
        }
      }
    }
  });

  const book = {
    SheetNames: [sheetname],
    Sheets: {
      [sheetname]: sheet,
    },
  };
  XLSXS.writeFile(book, filename);
}

export const read_csv = async (file) => {
  let csvstr = await readFile(file, true);
  let lines = csvstr.split("\r\n");
  const keyMapper = { q_t: "流量(m³/s)", t: "时间", z_t: "水位(米)" };
  for (var key in keyMapper) {
    lines[0] = lines[0].replace(keyMapper[key], key);
  }
  let head = lines[0].trimEnd().split(",");
  let result = [];
  for (var i = 1; i < lines.length - 1; i++) {
    let obj = {};
    let values = lines[i].trimEnd().split(",");
    for (var j = 0; j < head.length; j++) obj[head[j]] = values[j];
    result.push(obj);
  }
  return result;
};

/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
*/
export const read_xls = async (file, sheetIndex, keyMapper) => {
  let data = await readFile(file, false);
  let workbook = xlsx.read(data, { type: "binary", cellDates: true });
  let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
  data = xlsx.utils.sheet_to_json(worksheet);
  return toSystemData(data, keyMapper);
};

export function write_csv(filename, data) {
  const keyMapper = { q_t: "流量(m³/s)", t: "时间", z_t: "水位(米)" };
  for (var key in keyMapper) {
    data[0] = data[0].replace(key, keyMapper[key]);
  }
  const blob = new Blob(["\ufeff" + data.map(String).join("\r\n")], {
    type: "text/plain;charset=utf-8",
  });
  saveFile(filename, blob);
}

export function write_xls(filename, sheetname, data, keyMapper) {
  const sheet = xlsx.utils.json_to_sheet(toExportData(data, keyMapper));
  const book = {
    SheetNames: [sheetname],
    Sheets: {
      [sheetname]: sheet,
    },
  };
  debugger
  xlsx.writeFile(book, filename);
}

export function saveFile(filename, blob) {
  let navi = window.navigator;
  if (navi && navi.msSaveOrOpenBlob) {
    // IE10+
    navi.msSaveOrOpenBlob(blob, filename);
  } else {
    // 非IE浏览器
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    link.click();
    window.URL.revokeObjectURL(link.href);
  }
}

export function getExtention(filename) {
  if (!filename || filename == "") return "";
  var infos = filename.split(".");
  if (infos.length < 2) return "";
  var ext = infos[infos.length - 1];
  return ext.toLowerCase();
}

export function getFilename(filename) {
  var ext = getExtention(filename);
  return filename.replace("." + ext, "");
}

export function getFileIcon(filename) {
  var ext = getExtention(filename);
  if (ext === "pdf") return "PDF";
  if (ext === "doc" || ext === "docx") return "WORD";
  if (ext === "xls" || ext === "xlsx") return "xls";
  return "unknow";
}
